$(function () {
    const id = window.sessionStorage.getItem('id')
    testLogin()
    async function testLogin() {
        // console.log(token,'||||',id,user_id);
        const res = await $.ajax({
            url: 'http://localhost:6060/users/info/' + id,
            method: 'GET',
        })
        bindHtml(res)
    }
    function bindHtml(res) {
        $('.avatar img').prop('src', 'http://localhost:8080' + res.info.avatar)
        $('.username').val(res.info.username)
        $('.age').val(res.info.age)
        $('.nickname').val(res.info.nickname)
        $('.gender').val(res.info.gender)
    }
    $('.avatar input[type=file]').on('change', function () {
        // 利用 FileReader 读取文件信息, 展示在指定位置
        const fileInfo = this.files[0]

        if (!fileInfo) return

        if (fileInfo.type.split('/')[0] !== 'image') return this.value = ''

        const fr = new FileReader()
        fr.readAsDataURL(fileInfo)
        fr.onload = res => {
            // 展示出来
            $('.avatar img').prop('src', res.currentTarget.result)
            $(this).prev().css('background-image', `url(${res.currentTarget.result})`)
        }
    })
    $('form').on('submit', async e => {
        e.preventDefault()
        console.log($('.avatar img').prop('src'));
        const fm = new FormData($('form')[0])
        fm.append('id',id) 
        console.log(fm);
        // fm.append("img_url",)
        const res = await $.ajax({
            url: 'http://localhost:6060/users/update',
            data: fm,
            processData: false,
            contentType: false,
            method: 'post',
        })
        console.log(res);
        testLogin()
    })
})